package encrypt

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"gitee.com/ichub/goconfig/common/base/basedto"
	"gitee.com/ichub/goconfig/common/ichublog"
	"github.com/forgoer/openssl"
	"io"
)

// https://www.lesscode.work/GoCMS/
const (
	KEY_STR   = "ichub20240401"
	iceasyApi = "https://host.iceasy.com/external/api/product/ichub/ajaxList"
)

var EncDecInst = NewEncDec()

type EncDec struct {
	basedto.BaseEntity

	salt string
}

func NewEncDec() *EncDec {
	return &EncDec{}
}

func (this *EncDec) makeSalt() string {
	md5Hash := md5.New()
	md5Hash.Write([]byte(KEY_STR))
	dataHash := md5Hash.Sum(nil)
	salt := hex.EncodeToString(dataHash[:16])
	this.salt = salt
	return salt

}
func (this *EncDec) Md5Encrypt(text string) string {
	h := md5.New()
	io.WriteString(h, text)
	sum := h.Sum(nil)

	return hex.EncodeToString(sum[:])
}

func (this *EncDec) AesEnc(text string, salt string) []byte {
	aesStr, err := openssl.AesECBEncrypt([]byte(text), []byte(salt), openssl.PKCS7_PADDING)
	if err != nil {
		ichublog.Error(err)
	}
	return aesStr
}

func (this *EncDec) AesDec(text string, salt string) []byte {
	aesStr, err := openssl.AesECBDecrypt([]byte(text), []byte(salt), openssl.PKCS7_PADDING)
	if err != nil {
		ichublog.Error(err)
	}
	return aesStr
}

func (this *EncDec) AesEncBase64(text string) string {
	var salt = this.makeSalt()
	aesStr := this.AesEnc(text, salt)
	return base64.StdEncoding.EncodeToString(aesStr)
}

func (this *EncDec) AesDecBase64(text string) string {
	var salt = this.makeSalt()
	bytes, _ := base64.StdEncoding.DecodeString(text)
	var aesStr = this.AesDec(string(bytes), salt)

	return string(aesStr)
}
func (this *EncDec) EncBase64(text string) string {

	return this.AesEncBase64(text)
}

func (this *EncDec) DecBase64(text string) string {
	return this.AesDecBase64(text)
}
